<template>
  <div class="bookview">
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="图书名称">
        <el-input v-model="formInline.bookname" placeholder="图书名称"></el-input>
      </el-form-item>
      <el-form-item label="作者名称">
        <el-input v-model="formInline.bookauthor" placeholder="作者名称"></el-input>
      </el-form-item>
      <el-form-item label="分类">
        <el-select v-model="formInline.booktypeid" placeholder="请选择">
          <el-option label="全部类型" value=""></el-option>
          <el-option
              v-for="c1 in level1"
              :key="c1.booktypeid"
              :label="c1.booktypename"
              :value="c1.booktypeid"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
        <el-button type="primary" @click="onAdd">新增</el-button>
      </el-form-item>
    </el-form>
    <el-table
        :data="tableData"
        style="width: 100%">
      <el-table-column
          prop="bookname"
          label="图书名称">
      </el-table-column>
      <el-table-column
          prop="bookauthor"
          label="作者名称">
      </el-table-column>
      <el-table-column
          label="logo">
        <template slot-scope="scope">
          <img :src="baseurl+'/'+scope.row.bookimg" alt="" style="height: 50px;width: 50px">
        </template>
      </el-table-column>
      <el-table-column
          label="分类">
        <template slot-scope="scope">
          {{scope.row.booktypename}}
        </template>
      </el-table-column>
      <el-table-column
          label="状态">
          <template slot-scope="scope">
            {{ scope.row.isborrowed == 0 ? '未借出':'已借出' }}
          </template>
      </el-table-column>
      <el-table-column
          label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="toUpdate(scope.row)">修改</el-button>
          <el-upload
              class="upload-demo"
              name="logo"
              method="post"
              accept="image/*"
              :before-upload="beforeUpload"
              :file-list="filelist"
              :show-file-list="false"
              :on-success="uploadSuccess"
              :action="baseurl+'/bookinfo/upLogo/'+scope.row.bookid"
              multiple
              :limit="1">
            <el-button size="small" type="warning">上传</el-button>
          </el-upload>

          <el-button size="mini" type="danger" @click="toDel(scope.row.bookid)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        background

        :current-page="pagenum"
        :page-size="5"
        @current-change="changepagenum"
        :page-count="pages"
        layout="prev, pager, next"
        :total="total">
    </el-pagination>
    <el-dialog
        title="新增/修改"
        :visible.sync="dialogVisible"
        width="60%"
        :before-close="handleClose">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="图书名称" prop="bookname">
          <el-input v-model="ruleForm.bookname"></el-input>
        </el-form-item>
        <el-form-item label="作者姓名" prop="bookauthor">
          <el-input v-model="ruleForm.bookauthor"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="bookprice">
          <el-input v-model.number="ruleForm.bookprice" type="number" placeholder="请输入价格"></el-input>
        </el-form-item>
        <el-form-item label="图书描述" prop="bookdesc">
          <el-input
              v-model="ruleForm.bookdesc"
              type="textarea"
              placeholder="请输入图书描述"
              :rules="{ required: true, message: '描述必填', trigger: 'blur' }"
          ></el-input>
        </el-form-item>
        <el-form-item label="借阅状态" prop="isborrowed">
          <el-radio-group v-model.number="ruleForm.isborrowed">
            <el-radio :label="0">未借出</el-radio>
            <el-radio :label="1">已借出</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="分类">
          <el-select v-model="ruleForm.booktypeid" placeholder="请选择">
            <el-option label="全部类型" :value="8"></el-option>
            <el-option
                v-for="c1 in addlevel1"
                :key="c1.booktypeid"
                :label="c1.booktypename"
                :value="c1.booktypeid"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>

import {delbook, getbookinfopage, getbookType, saveOrUpdateBook, validateBookname} from "@/api/api";

export default {
  name: 'BookView',
  data() {


    return {
      filelist:[],
      dialogVisible: false,
      // 修正：ruleForm 改为对象属性（移除括号）
      ruleForm: {
        bookid: '',
        bookname: '',
        bookauthor: '',
        booktypename:'',
        bookprice: 0,
        bookdesc: '',
        isborrowed: 0,
      },
      rules: {
        bookname: [
        { required: true, message: '请输入图书名称', trigger: 'blur' },
        { validator: this.checkBooknameUnique, trigger: 'blur' }
        ],
        bookauthor: [
          { required: true, message: '请输入作者姓名', trigger: 'blur' }
        ],
        bookprice: [
          { required: true, message: '请输入价格', trigger: 'blur' },
          { type: 'number', message: '价格必须为数字', trigger: 'blur' }
        ]
      },
      baseurl:process.env.VUE_APP_BASE_API,
      tableData: [],
      level1: [],
      addlevel1: [],
      pages: 0,
      total: 0,
      pagenum: 1,
      formInline: {
        bookname: '',
        bookauthor: '',
        booktypeid: ''
      }
    };
  },
  methods: {
    beforeUpload(file){
      const isImage = file.type.startsWith('image/');
      if(!isImage){
        this.$message.error('只能上传图片文件！');
      }
      return isImage;
    },

    uploadSuccess(response,file,fileList){
      console.log(response);
      console.log(file);
      console.log(fileList);
      this.filelist=[]
      this.getpage()
    },

    checkBooknameUnique(rule, value, callback) {
      if (!value) {
        return callback(new Error('请输入图书名称'));
      }

      // 调用验证 API
      validateBookname(value, this.ruleForm.bookid)
          .then(res => {
            if (res.code === 200 && res.data) {
              callback(); // 名称可用
            } else {
              callback(new Error('图书名称已存在')); // 名称已存在
            }
          })
          .catch(err => {
            console.error('验证失败', err);
            callback(new Error('验证失败，请重试'));
          });
    },

    changepagenum(value) {
      this.pagenum = value;
      this.getpage();
    },
    getpage() {
      getbookinfopage(this.formInline, this.pagenum).then(res => {
        console.log(res);
        if (res.code === 200) {
          this.tableData = res.data.list;
          this.pages = res.data.pages;
          this.total = res.data.total;
          this.pagenum = res.data.pageNum;
        }
      });
    },
    getTree() {
      getbookType().then(res => {
        console.log(res);
        this.level1 = res.data.children;
        this.addlevel1 = res.data.children;
      });
    },
    onSubmit() {
      this.pagenum = 1;
      this.getpage();
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          saveOrUpdateBook(this.ruleForm)
              .then(res => {
                console.log(res);
                this.getpage(); // 刷新列表
                this.dialogVisible = false; // 关闭弹窗
              })
              .catch(err => {
                console.error('提交失败', err);
                // 可选：失败时不关闭弹窗，显示错误提示
              });
        } else {
          console.log('验证失败');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    onAdd() {
      this.ruleForm = {
        bookid: '',        // 清空 ID（新增时无需 ID）
        bookname: '',
        bookauthor: '',
        bookprice: 0,      // 价格重置为 0
        bookdesc: '',
        isborrowed: 0,     // 借阅状态默认未借出
        booktypeid: '',    // 分类 ID 清空
        booktypename: ''   // 分类名称清空（可选，根据接口是否需要）
      };
      this.dialogVisible=true
    },
    toUpdate(row){
      this.ruleForm = {
        bookid: row.bookid,
        bookname: row.bookname,
        bookauthor: row.bookauthor,
        bookprice: Number(row.bookprice), // 转换为数字
        bookdesc: row.bookdesc,
        isborrowed: Number(row.isborrowed), // 确保借阅状态为数字
        booktypeid: row.booktypeid, // 分类 ID 应为数字或字符串（根据接口定义）
        booktypename: row.booktypename
      };


      this.dialogVisible=true
    },
    handleClose(done) {
      done(); // 关闭弹窗
    },
    toDel(bookid) {

      this.$confirm('此操作将永久删除该图书, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delbook(bookid).then( res=>{
          console.log(res)

          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getpage()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });

    },
  },


  toUpdate() {

  },

  created() {
    this.getpage();
    this.getTree();
  },


};
</script>
